<template>
  <div class="message-board-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><ChatDotRound /></el-icon>
            <span class="header-title">留言板</span>
          </div>
        </div>
      </template>

      <!-- 用户信息卡片 -->
      <el-card class="user-info-card" shadow="never">
        <div class="user-info-wrapper">
          <el-avatar 
            :size="60" 
            :src="formatImageUrl(userInfo.avatar)"
            class="user-avatar-large"
          >
            <el-icon><User /></el-icon>
          </el-avatar>
          <div class="user-info-details">
            <div class="user-name-large">{{ userInfo.nickname || userInfo.username || '用户' }}</div>
            <div class="user-meta">
              <span class="meta-item">
                <el-icon><Message /></el-icon>
                <span>留言数: {{ myMessagesCount }}</span>
              </span>
              <span class="meta-item">
                <el-icon><Calendar /></el-icon>
                <span>加入时间: {{ formatTime(userInfo.createTime) }}</span>
              </span>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 选项卡 -->
      <el-tabs v-model="activeTab" class="message-tabs">
        <!-- 留言板选项卡 -->
        <el-tab-pane label="留言板" name="board">
          <!-- 发布留言区域 -->
          <div class="publish-section">
            <el-input
              type="textarea"
              v-model="newMsg"
              placeholder="说点什么吧..."
              :rows="4"
              maxlength="500"
              show-word-limit
              class="message-input"
            />
            <div class="publish-actions">
              <el-button 
                type="primary" 
                @click="submitMessage"
                :loading="submitting"
                :icon="Promotion"
              >
                发布留言
              </el-button>
            </div>
          </div>

          <el-divider />

          <!-- 留言列表 -->
          <div class="messages-list" v-loading="loading">
            <div 
              v-for="item in messages" 
              :key="item.id" 
              class="message-item"
            >
              <div class="message-header">
                <div class="user-info">
              <el-avatar 
                :size="40" 
                :src="formatImageUrl(getUserAvatar(item))"
                class="user-avatar"
              >
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="user-details">
                <span class="user-name">
                  {{ getUserDisplayName(item) }}
                </span>
                <span class="message-time">{{ formatTime(item.createTime) }}</span>
              </div>
                </div>
              </div>
              <div class="message-content">
                <p>{{ item.content }}</p>
              </div>
              <div v-if="item.reply" class="message-reply">
                <div class="reply-header">
                  <el-icon class="reply-icon"><Avatar /></el-icon>
                  <span class="reply-label">管理员回复</span>
                </div>
                <p class="reply-content">{{ item.reply }}</p>
              </div>
            </div>

            <!-- 空状态 -->
            <el-empty 
              v-if="!loading && messages.length === 0" 
              description="暂无留言，快来发表第一条留言吧！"
              :image-size="120"
            />
          </div>
        </el-tab-pane>

        <!-- 我的留言选项卡 -->
        <el-tab-pane label="我的留言" name="myMessages">
          <div class="messages-list" v-loading="myLoading">
            <div 
              v-for="item in myList" 
              :key="item.id" 
              class="message-item my-message-item"
            >
              <div class="message-header-with-action">
                <div class="message-time-header">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatTime(item.createTime) }}</span>
                </div>
                <el-button 
                  size="small" 
                  type="danger" 
                  :icon="Delete"
                  circle
                  @click="deleteMyMessage(item.id)"
                  :loading="deletingIds.includes(item.id)"
                  class="delete-btn"
                  title="删除留言"
                />
              </div>
              <div class="message-content">
                <p>{{ item.content }}</p>
              </div>
              <div v-if="item.reply" class="message-reply">
                <div class="reply-header">
                  <el-icon class="reply-icon"><Avatar /></el-icon>
                  <span class="reply-label">管理员回复</span>
                </div>
                <p class="reply-content">{{ item.reply }}</p>
                <span class="reply-time" v-if="item.replyTime">
                  {{ formatTime(item.replyTime) }}
                </span>
              </div>
              <div v-else class="no-reply">
                <el-tag type="info" size="small" effect="plain">等待管理员回复</el-tag>
              </div>
            </div>

            <!-- 空状态 -->
            <el-empty 
              v-if="!myLoading && myList.length === 0" 
              description="您还没有留言记录"
              :image-size="120"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { ChatDotRound, Promotion, User, Avatar, Message, Calendar, Clock, Delete } from "@element-plus/icons-vue";

const newMsg = ref("");
const messages = ref([]);
const myList = ref([]);
const loading = ref(false);
const myLoading = ref(false);
const submitting = ref(false);
const activeTab = ref("board");
const userId = localStorage.getItem("userId");
const deletingIds = ref([]); // 正在删除的留言ID列表

const userInfo = ref({
  id: null,
  username: '',
  nickname: '',
  avatar: '',
  createTime: ''
});

// 用户信息缓存，key为userId，value为用户信息
const userInfoCache = ref({});

const formatImageUrl = (url) => {
  if (!url) return '';
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  return `http://localhost:8080${url.startsWith('/') ? url : '/' + url}`;
};

const formatTime = (time) => {
  if (!time) return '';
  if (typeof time === 'string' && time.includes('T')) {
    return time.replace('T', ' ').substring(0, 19);
  }
  return time;
};

// 获取用户信息（从缓存或留言数据中）
const getUserInfoFromMessage = (item) => {
  if (!item) return null;
  
  // 先尝试从留言数据中直接获取
  if (item.nickname || item.userName || item.username) {
    return {
      nickname: item.nickname || item.userName || item.username,
      avatar: item.avatar || item.userAvatar || item.user?.avatar
    };
  }
  
  // 如果有userId，从缓存中获取
  const userId = item.userId || item.user?.id;
  if (userId && userInfoCache.value[userId]) {
    return userInfoCache.value[userId];
  }
  
  return null;
};

// 获取用户显示名称
const getUserDisplayName = (item) => {
  const userInfo = getUserInfoFromMessage(item);
  if (userInfo) {
    return userInfo.nickname || userInfo.userName || userInfo.username || '匿名用户';
  }
  
  // 尝试直接从item中获取
  return item.userName || 
         item.nickname || 
         item.userNickname || 
         item.username ||
         item.user?.nickname || 
         item.user?.userName || 
         item.user?.username ||
         item.user?.nickName ||
         '匿名用户';
};

// 获取用户头像
const getUserAvatar = (item) => {
  const userInfo = getUserInfoFromMessage(item);
  if (userInfo) {
    return userInfo.avatar || userInfo.userAvatar || '';
  }
  
  // 尝试直接从item中获取
  return item.avatar || 
         item.userAvatar || 
         item.user?.avatar ||
         item.user?.userAvatar ||
         '';
};

// 根据userId查询用户信息
const loadUserInfoById = async (userId) => {
  if (!userId || userInfoCache.value[userId]) {
    return userInfoCache.value[userId];
  }
  
  try {
    const res = await axios.get(`http://localhost:8080/api/user/${userId}`);
    if (res.data.code === 200 && res.data.data) {
      userInfoCache.value[userId] = res.data.data;
      return res.data.data;
    }
  } catch (error) {
    console.error(`加载用户信息失败 (userId: ${userId}):`, error);
  }
  return null;
};

// 批量加载用户信息
const loadUsersForMessages = async (messagesList) => {
  if (!messagesList || messagesList.length === 0) return;
  
  // 收集所有需要查询的userId
  const userIds = new Set();
  messagesList.forEach(item => {
    const userId = item.userId || item.user?.id;
    if (userId && !userInfoCache.value[userId]) {
      userIds.add(userId);
    }
  });
  
  // 并发查询所有用户信息
  if (userIds.size > 0) {
    const promises = Array.from(userIds).map(userId => loadUserInfoById(userId));
    await Promise.all(promises);
  }
};


const myMessagesCount = computed(() => {
  return myList.value.length;
});

// 加载用户信息
const loadUserInfo = async () => {
  if (!userId) return;
  
  try {
    const res = await axios.get(`http://localhost:8080/api/user/${userId}`);
    if (res.data.code === 200) {
      userInfo.value = res.data.data || {};
    }
  } catch (error) {
    console.error('加载用户信息失败:', error);
  }
};

const loadMessages = async () => {
  loading.value = true;
  try {
    const res = await axios.get("http://localhost:8080/api/message/list");
    if (res.data.code === 200) {
      messages.value = res.data.data || [];
      // 调试：打印第一条数据看看结构
      if (messages.value.length > 0) {
        console.log('留言数据示例:', messages.value[0]);
      }
      // 加载用户信息
      await loadUsersForMessages(messages.value);
    } else {
      ElMessage.error(res.data.msg || '获取留言列表失败');
    }
  } catch (error) {
    console.error('加载留言失败:', error);
    ElMessage.error('加载留言失败');
  } finally {
    loading.value = false;
  }
};

const loadMyMessages = async () => {
  if (!userId) return;
  
  myLoading.value = true;
  try {
    const res = await axios.get("http://localhost:8080/api/message/my", { 
      params: { userId } 
    });
    if (res.data.code === 200) {
      myList.value = res.data.data || [];
    } else {
      ElMessage.error(res.data.msg || '获取我的留言失败');
    }
  } catch (error) {
    console.error('加载我的留言失败:', error);
  } finally {
    myLoading.value = false;
  }
};

const submitMessage = async () => {
  if (!newMsg.value.trim()) {
    ElMessage.warning("请输入留言内容");
    return;
  }
  
  submitting.value = true;
  try {
    const payload = {
      userId: Number(userId),
      content: newMsg.value.trim()
    };
    
    const res = await axios.post("http://localhost:8080/api/message/add", payload);
    if (res.data.code === 200) {
      ElMessage.success("留言成功");
      newMsg.value = "";
      // 延迟一下再加载，确保后端已保存
      setTimeout(() => {
        loadMessages();
        loadMyMessages(); // 刷新我的留言列表
      }, 300);
    } else {
      ElMessage.error(res.data.msg || '发布留言失败');
    }
  } catch (error) {
    console.error('发布留言失败:', error);
    ElMessage.error('发布留言失败');
  } finally {
    submitting.value = false;
  }
};

const deleteMyMessage = async (messageId) => {
  try {
    await ElMessageBox.confirm('确定删除这条留言吗？删除后无法恢复。', '提示', {
      type: 'warning',
      confirmButtonText: '确定删除',
      cancelButtonText: '取消'
    });
    
    deletingIds.value.push(messageId);
    try {
      const res = await axios.delete(`http://localhost:8080/api/message/admin/delete`, {
        params: { id: messageId }
      });
      if (res.data.code === 200) {
        ElMessage.success('删除成功');
        loadMessages();
        loadMyMessages();
      } else {
        ElMessage.error(res.data.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除留言失败:', error);
      ElMessage.error('删除失败');
    } finally {
      deletingIds.value = deletingIds.value.filter(id => id !== messageId);
    }
  } catch (error) {
    // 用户取消删除
  }
};

onMounted(async () => {
  await loadUserInfo();
  loadMessages();
  loadMyMessages();
});
</script>

<style scoped>
.message-board-page {
  padding: 20px 40px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
  min-height: 100%;
}

.main-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.main-card :deep(.el-card__body) {
  padding: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 22px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

/* 用户信息卡片 */
.user-info-card {
  margin-bottom: 24px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.user-info-card :deep(.el-card__body) {
  padding: 20px;
}

.user-info-wrapper {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar-large {
  flex-shrink: 0;
  border: 3px solid rgba(255, 255, 255, 0.3);
}

.user-info-details {
  flex: 1;
  color: white;
}

.user-name-large {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
}

.user-meta {
  display: flex;
  gap: 20px;
  font-size: 14px;
  opacity: 0.9;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 选项卡样式 */
.message-tabs {
  margin-top: 20px;
}

.message-tabs :deep(.el-tabs__header) {
  margin-bottom: 20px;
}

.message-tabs :deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
}

/* 发布留言区域 */
.publish-section {
  margin-bottom: 24px;
  padding: 20px;
  background: #fafbfc;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
}

.message-input {
  margin-bottom: 12px;
}

.message-input :deep(.el-textarea__inner) {
  border-radius: 10px;
  border: 2px solid #e4e7ed;
  padding: 14px;
  font-size: 14px;
  line-height: 1.8;
  resize: none;
  transition: all 0.3s ease;
}

.message-input :deep(.el-textarea__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.publish-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.messages-list {
  min-height: 200px;
  padding: 10px 0;
}

.message-item {
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 16px;
  transition: all 0.3s ease;
  position: relative;
}

.message-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  border-radius: 12px 0 0 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.message-item:hover::before {
  opacity: 1;
}

.message-item:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
  border-color: #c6e2ff;
}

.message-header {
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  flex-shrink: 0;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: 600;
  color: #303133;
  font-size: 15px;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-time-header {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #909399;
}

.message-header-with-action {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.my-message-item:hover .delete-btn {
  opacity: 1;
}


.message-content {
  margin: 12px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.8;
  word-break: break-word;
}

.message-content p {
  margin: 0;
}

.message-reply {
  margin-top: 16px;
  padding: 16px;
  background: #f0f9ff;
  border-left: 3px solid #409eff;
  border-radius: 6px;
  position: relative;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
}

.reply-icon {
  color: #409eff;
  font-size: 16px;
}

.reply-label {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.reply-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin: 0 0 8px 0;
}

.reply-time {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.no-reply {
  margin-top: 16px;
}
</style>

